﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TL_Cloud.Core.Extensions;
using TL_Cloud.Core.Interfaces;
using TL_Cloud.Models.BookShop;
using TL_Cloud.RepositoryInterface.BookShop;
using TL_Cloud.ViewModels.BookShop.BKBuyInfo;
using TL_Cloud.ViewModels.BookShop.BKCollect;
using TL_Cloud.ViewModels.BookShop.BKComment;
using TL_Cloud.ViewModels.BookShop.BKDownLoadRecord;
using TL_Cloud.ViewModels.BookShop.BKPics;

namespace TL_Cloud.API.Controllers
{
    /// <summary>
    /// 图书图片信息
    /// </summary>
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class BKPicsController : ControllerBase
    {
        private readonly ILogger logger;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IBKPicsRepository _repository;
        private readonly IUrlHelper _urlHelper;

        public BKPicsController(
            ILogger<BKInfoController> logger,
            IBKPicsRepository repository,
            IUnitOfWork unitOfWork
            )
        {

            this.logger = logger;
            this._repository = repository;
            this._unitOfWork = unitOfWork;
        }
        /// <summary>
        /// 获取所有的图书的图片信息
        /// 搜索条件是:bookId
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        [HttpGet(Name = "GetBKPics")]
        public async Task<IActionResult> Get([FromQuery]BKPicsQueryParameters parameters)
        {

            var dataList = await _repository.GetAllEntitiesAsync(parameters);

            //数据返回分页数据
            var meta = new
            {
                dataList.TotalItemsCount,
                dataList.PageSize,
                dataList.PageIndex,
                dataList.PageCount,
            };

            Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(meta, new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            }));
            //返回结果塑性
            return Ok(dataList.ToDynamicIEnumerable(parameters.Fields));
        }


        /// <summary>
        /// 更新图书图片信息
        /// </summary>  
        /// <param name="jobj"> json对象
        /// {
        /// BookId：'', //图书编号
        /// PicName:'', //图书缩略图名称
        /// PicUrl:'', //图书苏略图的地址
        /// IsDelete:0或1 //是否删除
        /// }
        /// </param>
        [HttpPost(Name = "CreateBkPic")]
        public async Task<IActionResult> Post([FromBody] JObject jobj)
        {
            if (jobj == null)
            {
                return BadRequest();
            }
            if (Convert.ToBoolean(jobj["IsDelete"]) == false)  //增加数据
            {
                var entity = new Bk_Pics();
                entity.BookId = jobj["BookId"].ToString();
                entity.PicName = jobj["PicName"].ToString();
                entity.PicUrl = jobj["PicUrl"].ToString();
                var userinfo = this.GetUserInfo();
                entity.Create(userinfo.Item1, userinfo.Item2);
                _repository.Add(entity);
            }
            else //删除数据
            {
                var dataList = await _repository.GetAllEntitiesAsync(new BKPicsQueryParameters
                {
                    isPage = false,
                    BookId = jobj["BookId"].ToString(),
                    PicUrl = jobj["PicUrl"].ToString(),
                    PicName = jobj["PicName"].ToString()
                });
                foreach (var item in dataList)
                {
                    _repository.Delete(item);
                }
            }

            if (!await _unitOfWork.SaveAsync())
            {
                throw new Exception("Save Failed!");
            } 
            return NoContent();
        }

       
        ///// <summary>
        ///// 删除图书图片信息
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpDelete("{id}", Name = "DeleteBKPic")]
        //public async Task<IActionResult> Delete(string id)
        //{
        //    var post = await _repository.GetEntityByIdAsync(id);
        //    if (post == null)
        //    {
        //        return NotFound();
        //    }
        //    _repository.Delete(post);

        //    if (!await _unitOfWork.SaveAsync())
        //    {
        //        throw new Exception($"Deleting entity {id} failed when saving.");
        //    }

        //    return NoContent();
        //}
    }
}
